# coding:utf-8
import json

import requests
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QHBoxLayout, QButtonGroup
from qfluentwidgets import BodyLabel, setFont, LineEdit, PushButton, FluentIcon as FIF, TransparentToolButton

from common import SingleIcon, cfg
from components import BaseScrollArea, FlowTitleCard
from components.media import VideoGraphicsView


def get_video_info(jx_url: str):
    url = 'https://m1-a1.cloud.nnpp.vip:2223/api/v/'
    params = {
        'z': cfg.get(cfg.videoParseKey),
        # 'jx': 'https://v.qq.com/x/cover/mcv8hkc8zk8lnov/x0036x5qqsr.html',
        'jx': jx_url,
        's1ig': '11401',
        'g': ''
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
    }
    response = requests.get(url, params=params, headers=headers)
    response.raise_for_status()
    response.encoding = 'utf-8'
    try:
        return json.loads(response.text)
    except json.JSONDecodeError as e:
        return response.text


class VideoParseView(BaseScrollArea):
    title = '视频解析'
    description = '解析视频信息，获取视频下载地址，支持腾讯视频、爱奇艺、优酷等视频网站。（不是很稳定，请谨慎使用）'
    object_name = 'VideoParseView'
    icon = SingleIcon.VIDEO

    def __init__(self, parent=None):
        super().__init__(parent)
        self.titleLabel = BodyLabel(self.title, self)
        self.settingsButton = TransparentToolButton(FIF.SETTING, self)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()
        self.jtUrlLineEdit = LineEdit(self)
        self.parseButton = PushButton(FIF.SEARCH, '解析', self)
        self.videoGraphicsView = VideoGraphicsView(self)
        self.buttonGroup = QButtonGroup(self)
        self.__initWidgets()

    def __initWidgets(self):
        self.setReturnVisible(True)
        setFont(self.titleLabel, 26)
        self.jtUrlLineEdit.setPlaceholderText('请输入视频地址')
        self.jtUrlLineEdit.setClearButtonEnabled(True)

        # connect signals
        self.parseButton.clicked.connect(self.onParsed)
        self.buttonGroup.buttonClicked.connect(self.onButtonClicked)
        # add widgets to layout
        self.horizontalLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.settingsButton, 0, Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout_2.addWidget(self.jtUrlLineEdit)
        self.horizontalLayout_2.addWidget(self.parseButton)
        self.scrollLayout.addLayout(self.horizontalLayout)
        self.scrollLayout.addLayout(self.horizontalLayout_2)
        self.scrollLayout.addWidget(self.videoGraphicsView)

    def onParsed(self):
        jx_url = self.jtUrlLineEdit.text()
        if not jx_url:
            return
        self.load(get_video_info, jx_url)

    def __addHomeButton(self, card: FlowTitleCard, item: dict):
        name = item.get('name', '')
        year = item.get('year', '')
        eps = item.get('source', {}).get('eps', [])
        if not eps:
            return
        for ep in eps:
            name2 = ep.get('name', '')
            button = card.addButton(f'{name} - {year} - {name2}', ep['url'])
            self.buttonGroup.addButton(button)

    def onFuncSuccess(self, result: dict):
        if isinstance(result, str):
            print(result)
            return
        print(result)
        tp = result.get('type')
        if tp == 'home':
            card = FlowTitleCard(self)
            self.scrollLayout.addWidget(card)
            card.setTitle('最新更新')
            for item in result.get('new', []):
                self.__addHomeButton(card, item)
            for item in result.get('hot', []):
                self.__addHomeButton(card, item)

        elif tp == 'tv':
            dataList = result.get('data')
            for item in dataList:
                card = FlowTitleCard(self)
                self.scrollLayout.addWidget(card)
                title = item.get('name', '') + '   ' + item.get('year', '')
                card.setTitle(title)
                for ep in item['source']['eps']:
                    button = card.addButton(ep['name'], ep['url'])
                    self.buttonGroup.addButton(button)
        elif tp == 'movie':
            print(result)

    def onButtonClicked(self, button: PushButton):
        url = button.property('data')
        self.videoGraphicsView.stop()
        self.videoGraphicsView.setSource(url)
        self.videoGraphicsView.play()


if __name__ == '__main__':
    url = 'https://www.iqiyi.com/v_1wcgo089jdo.html'
    print(get_video_info(url))
